import re

from django.shortcuts import render,HttpResponse
import random
from utils.tencent.sms import send_sms_single
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from app01 import forms
from django_redis import get_redis_connection

# 正则校验手机号规则
def phone_validator(value):
    if not re.match(r"^(1[3|4|5|6|7|8|9])\d{9}$",value):
        raise str('手机格式错误')

@csrf_exempt
def send_sms(request):
    '''
    发送短信
    :param request:
    :return:
    '''

    tpl=request.POST.get('tpl') #短信格式模板名称，login register
    phone_num=request.POST.get('phone')
    # print(tpl,phone_num)
    template_id= settings.TENCENT_SMS_TEMPLAE.get(tpl) #TENCENT_SMS_TEMPLAE={"login":1393005,"register":1393004}

    if not template_id:
        return HttpResponse("template is not exist")

    if not re.match(r"^(1[3|4|5|6|7|8|9])\d{9}$", phone_num):
        return HttpResponse("the phone_num is err")

    code=random.randint(1000,9999)
    # phone_num='15605390272'
    # template_id='1393005'
    # res=send_sms_single(phone_num, template_id, [code,])
    res=dict()
    res['result']=0
    result_str='{},{},{}'.format(phone_num, template_id, [code,])
    print(result_str)
    if res['result']==0:
        # conn = get_redis_connection() # 连接redis ，默认是 default
        # conn.set(phone_num,code,ex=30) # 保存，设定时间30s
        print('success')
        return HttpResponse("success")
    else:
        return HttpResponse(res['errmsg'])

def register(request):
    if request.method=="POST":
        user_form=forms.RegisterModelForm(request.POST)
        # print(user_form)
        if user_form.is_valid():
            print(user_form)
        return HttpResponse('register is ok')
    if request.method=="GET":
        form=forms.RegisterModelForm()
        return render(request,'register.html',{'form':form})

'''
def register(request):
    if request.method == "POST":
        user_form = RegistrationForm(request.POST)
        userprofile_form = UserProfileForm(request.POST)
        if user_form.is_valid()*userprofile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data['password'])
            new_user.save()
            new_profile = userprofile_form.save(commit=False)
            new_profile.user = new_user
            new_profile.save()
            UserInfo.objects.create(user=new_user)
            #return HttpResponse("successfully")
            return HttpResponseRedirect(reverse("account:user_login"))
        else:
            return HttpResponse("sorry, your can not register.")
    else:
        user_form = RegistrationForm()
        userprofile_form = UserProfileForm()
        return render(request, "account/register.html", {"form": user_form, "profile":userprofile_form})
        
        '''